import axios from 'axios'
import {Loading,Message} from 'element-ui'
//import {delCookie, getCookie} from "./utils";

// axios 配置
axios.defaults.timeout = 5000;
let loadingInstance;
// http request 拦截器
axios.interceptors.request.use(
  config => {
    loadingInstance = Loading.service({
      text: '正在努力加载中',
      lock: true,
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    config.headers = {
      'Content-Type':'application/json',
       withCredentials: true
    };
    if(localStorage.getItem('Auth') != null && localStorage.getItem('Auth') != undefined) {
      config.headers['X-Auth-Token'] = localStorage.getItem('Auth')
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);


// http response 拦截器
axios.interceptors.response.use(
  response => {
    if(response.data.code === 20000) {
      loadingInstance.close();
      return response;
    } else {
      loadingInstance.close();
      Message({
        message: response.data.msg,
        type: 'error',
        showClose: true
      })
    }
  },
  error => {
    return Promise.reject(error)
  });

export default axios;

/**
 * fetch 请求方法
 * @param url
 * @param params
 * @returns {Promise}
 */
export function fetch(url, params = {}) {
  
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    })
      .then(response => {
        resolve(response.data);
      })
      .catch(error => {
        reject(error)
      })
  })
}

/**
 * post 请求方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err);
      })
  })
}

/**
 * patch 方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
export function patch(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.patch(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err);
      })
  })
}

/**
 * put 方法封装
 * @param url
 * @param data
 * @returns {Promise}
 */
export function put(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data)
      .then(response => {
        resolve(response.data);
      }, err => {
        reject(err);
      })
  })
}
